package com.ge.modules.api.controller;

import com.ge.common.annotation.LoginUserApi;
import com.ge.common.utils.*;
import com.ge.common.validator.Assert;
import com.ge.modules.api.apiDTO.TbOrderGetDto;
import com.ge.modules.api.service.*;
import com.ge.modules.entity.*;
import com.ge.utils.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 用户订单
 *
 * @author lanyonglin
 * @email www.baidu.com
 * @date 2018-04-11 17:28:43
 */
@RestController
@RequestMapping("/api/user/order")
public class TbOrderController {
    @Autowired
    private TbOrderService tbOrderService;

    @Autowired
    private TbCommodityService tbCommodityService;

    @Autowired
    private TbStoreService tbStoreService;

    @Autowired
    private TbTechnicianService tbTechnicianService;

    @Autowired
    private TbUserCardService userCardService;

    /**
     * 显示订单列表(可根据不同状态显示不同订单)
     *
     * @param tbUser
     * @param params
     * @return
     */
    @RequestMapping("/list")
    public R list(@LoginUserApi TbUser tbUser, @RequestParam Map<String, Object> params) {
        if (tbUser == null) {
            //设置换回编码为501 登录需要登录或者登录失效
            return R.error(501, "用户登录失效");
        }
        params.put("userId", tbUser.getUserId());
        //查询列表数据
        Query query = new Query(params);
        List<TbOrderEntity> tbOrderEntityList = tbOrderService.queryList(query);
        int total = tbOrderService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(tbOrderEntityList, total, query.getLimit(), query.getPage());
        return R.ok().put("data", pageUtil);
    }

    /**
     * 查询订单详细信息
     */
    @RequestMapping("/info/{orderCode}")
    public R info(@LoginUserApi TbUser tbUser, @PathVariable("orderCode") String orderCode) {
        if (tbUser == null) {
            //设置换回编码为501 登录需要登录或者登录失效
            return R.error(501, "用户登录失效");
        }
        //通过对象存储条件
        TbOrderEntity tbOrderEntity = new TbOrderEntity();
        tbOrderEntity.setOrderCode(orderCode);
        try {
            TbOrderEntity tbOrderEntity1 = tbOrderService.queryObject(tbOrderEntity);
            return R.ok().put("data", tbOrderEntity1);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 下单
     *
     * @param tbUser 用户对象
     * @param jsons  json条件
     * @return
     */
    @PostMapping("/save")
    public R save(@LoginUserApi TbUser tbUser, String jsons) {
        Assert.isBlank(jsons, "没有条件");
        try {
            //查询用户会员卡 是否有月卡 或者年卡
            TbUserCardEntity tbUserCardEntity = new TbUserCardEntity();
            tbUserCardEntity.setUserId(tbUser.getUserId());
            TbUserCardEntity userCardEntity = userCardService.queryByObject(tbUserCardEntity);
            Assert.isNull(userCardEntity, "会员卡不存在");
            Boolean month = false;
            Boolean year = false;
            //月卡
            if (userCardEntity.getMonthCardStartTime() != null && userCardEntity.getMonthCardEndTime() != null) {
                //如果过期了 就显示0天
                month = DateUtils.date_compare_date(userCardEntity.getMonthCardEndTime(), new Date());
            }
            //年卡
            if (userCardEntity.getYearCardStartTime() != null && userCardEntity.getYearCardEndTime() != null) {
                //如果过期了 就显示0天
                year = DateUtils.date_compare_date(userCardEntity.getYearCardEndTime(), new Date());
            }

            //订单总表
            TbOrderHeaderEntity orderHeaderEntity = new TbOrderHeaderEntity(OrderUtil.getOrderNo(), 0, new Date());
            //子订单列表
            List<TbOrderEntity> orderEntityList = new ArrayList<TbOrderEntity>();
            //解析json对象数组得到条件对象
            List<TbOrderGetDto> tbOrderGetDtoList = JsonUtils.jsonObj(jsons);
//			List<TbOrderGetDto> tbOrderGetDtoList = new JsonUtils<TbOrderGetDto>().jsonToListObj(jsons);
            //循环商品创建订单
            for (int i = 0; i < tbOrderGetDtoList.size(); i++) {
                TbOrderGetDto orderGetDto = tbOrderGetDtoList.get(i);
                TbCommodityEntity tbCommodityEntity = new TbCommodityEntity();
                tbCommodityEntity.setCommodityId(orderGetDto.getCommodityId());
                //查询商品
                TbCommodityEntity commodityEntity = tbCommodityService.queryObject(tbCommodityEntity);
                Assert.isNull(commodityEntity, "商品不存在");
                //根据商品的店铺编码查店铺 获取商品信息
                TbStoreEntity tbStoreEntity = new TbStoreEntity();
                tbStoreEntity.setStoreId(commodityEntity.getStoreId());
                TbStoreEntity storeEntity = tbStoreService.queryByObject(tbStoreEntity);
                //获取该订单的技师
                TbTechnicianEntity technicianEntity = new TbTechnicianEntity();
                //判断用户下单是否选择了技师
                if (orderGetDto.getTechnicianId() != null) {//选择了直接做查询
                    TbTechnicianEntity tbTechnicianEntity = new TbTechnicianEntity();
                    tbTechnicianEntity.setTechnicianId(orderGetDto.getTechnicianId());
                    technicianEntity = tbTechnicianService.queryByObject(tbTechnicianEntity);
                } else {//如果未选择技师 则通过商品需要的技师等级去查询技师列表 并随机指定一个
                    //根据店铺编码 技师等级查询技师列表
                    TbTechnicianEntity tbTechnicianEntity = new TbTechnicianEntity();
                    tbTechnicianEntity.setStoreId(commodityEntity.getStoreId());
                    tbTechnicianEntity.setGrade(commodityEntity.getTechnicianLevel());
                    List<TbTechnicianEntity> tbTechnicianEntityList = tbTechnicianService.queryListObject(tbTechnicianEntity);
                    if (tbTechnicianEntityList.size() <= 0) {
                        return R.error("没有技师！");
                    }
                    //随机找一个技师列表中的一个
                    int index = randomUtils.getNumber(0, tbTechnicianEntityList.size() - 1);
                    technicianEntity = tbTechnicianEntityList.get(index);
                }

                if (tbUser == null) {
                    //设置换回编码为501 登录需要登录或者登录失效
                    return R.error(501, "用户登录失效");
                }
                if (commodityEntity == null) {
                    return R.error("商品不存在");
                }
                if (technicianEntity == null) {
                    return R.error("技师不存在");
                }
                if (orderGetDto.getAppointmentTime() == null) {
                    return R.error("预约时间不能为空");
                }
                String buyerMassage = "";
                if (orderGetDto.getBuyerMassage() != null) {
                    buyerMassage = orderGetDto.getBuyerMassage();
                }
                //封装订单信息
                TbOrderEntity tbOrderEntity;
                //如果年卡没有过期 同时商品是美发类型的 同时小于680 都免费
                if (year && commodityEntity.getTypeOneCode() == 1 && commodityEntity.getDiscounts().compareTo(BigDecimal.valueOf(480)) == -1) {
                    tbOrderEntity = new TbOrderEntity(commodityEntity, tbUser, storeEntity,
                            technicianEntity, orderGetDto.getCommodityNumber(), orderGetDto.getAppointmentTime(),
                            buyerMassage, orderHeaderEntity.getOrderheaderCode());
                    //改为已支付 也就是待接单
                    tbOrderEntity.setOrderStatus(1);
                }
                //如果当前商品=38元 同时是美发类型 同时是美发类型下的理发类型 并且是会员 那么就将免费
                else if (month && commodityEntity.getTypeOneCode() == 1 && commodityEntity.getTypeTwoCode() == 1
                        && commodityEntity.getDiscounts().compareTo(BigDecimal.valueOf(38)) == -1) {
                    tbOrderEntity = new TbOrderEntity(commodityEntity, tbUser, storeEntity,
                            technicianEntity, orderGetDto.getCommodityNumber(), orderGetDto.getAppointmentTime(),
                            buyerMassage, orderHeaderEntity.getOrderheaderCode());
                    //改为已支付 也就是待接单
                    tbOrderEntity.setOrderStatus(1);
                } else {
                    tbOrderEntity = new TbOrderEntity(commodityEntity, tbUser, storeEntity,
                            technicianEntity, orderGetDto.getCommodityNumber(), orderGetDto.getAppointmentTime(),
                            buyerMassage, orderHeaderEntity.getOrderheaderCode());
                    //订单总价=订单总价+数量*子订单优惠价格
                    if (orderHeaderEntity.getOrderheaderPrice() != null) {
                        orderHeaderEntity.setOrderheaderPrice(orderHeaderEntity.getOrderheaderPrice().add(commodityEntity.getDiscounts().multiply(BigDecimal.valueOf(orderGetDto.getCommodityNumber()))));
                    } else {
                        orderHeaderEntity.setOrderheaderPrice(commodityEntity.getDiscounts().multiply(BigDecimal.valueOf(orderGetDto.getCommodityNumber())));
                    }
                }
                orderEntityList.add(tbOrderEntity);
            }
            //是否需要发起支付 1 支付 2 不支付
            int isPay = 1;
            //如果订单总价等于空
            if (orderHeaderEntity.getOrderheaderPrice() == null) {
                orderHeaderEntity.setOrderheaderPrice(BigDecimal.valueOf(0));
                isPay = 2;
            }
            tbOrderService.orderAndOrderHeader(orderEntityList, orderHeaderEntity);
            orderHeaderEntity.setIsPay(isPay);
            return R.ok().put("data", orderHeaderEntity);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 批量删除 做状态修改
     *
     * @param orderCodes 订单编号数组
     * @return
     */
    @RequestMapping("/deleteList")
    public R deleteList(@RequestBody Integer[] orderCodes) {
        tbOrderService.updateBatch(orderCodes);
        return R.ok();
    }

}
